package com.example.service;

import com.example.entity.Clazz;
import com.example.entity.Major;
import com.example.exception.CustomException;
import com.example.mapper.ClazzMapper;
import com.example.mapper.StudentMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ClazzService {
    @Resource
    private ClazzMapper clazzMapper;
    @Resource
    private StudentMapper studentMapper;

    public List<Clazz> selectAll(Clazz clazz) {
        return clazzMapper.selectAll(clazz);
    }

    public PageInfo<Clazz> selectPage(Clazz clazz, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Clazz> list = clazzMapper.selectAll(clazz);
        return PageInfo.of(list);
    }

    public void add(Clazz clazz) {
        if (clazzMapper.countByClassName(clazz.getClassName()) > 0){
            throw new CustomException("400","班级已存在");
        }
        clazzMapper.insert(clazz);
    }

    public void update(Clazz clazz) {
        Clazz exstingclazz = clazzMapper.selectById(clazz.getClassId());
        if (exstingclazz.getClassName().equals(clazz.getClassName())){
            if (exstingclazz.getMajorId().equals(clazz.getMajorId()) && exstingclazz.getTeacherId().equals(clazz.getTeacherId())){
                    return;
            }
        } else {
            if (clazzMapper.countByClassName(clazz.getClassName()) > 0){
                throw new CustomException("400","班级已存在");
            }
        }
        clazzMapper.update(clazz);
    }

    public void delete(Integer classId) {
        if (studentMapper.countByClassId(classId) > 0){
            throw new CustomException("400","存在关联学生");
        }
        clazzMapper.delete(classId);
    }

    public void deleteBatch(List<Integer> ids) {
        for (Integer classId : ids) {
            if (studentMapper.countByClassId(classId) > 0){
                throw new CustomException("400","存在关联学生");
            }
        }
        for (Integer classId : ids) {
            clazzMapper.delete(classId);
        }
    }
}
